package middlewares

import (
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/spf13/viper"
	"github.com/uber/jaeger-client-go"
	jaegercfg "github.com/uber/jaeger-client-go/config"
)

func Trace() gin.HandlerFunc {
	return func(context *gin.Context) {
		cfg := jaegercfg.Configuration{
			Sampler: &jaegercfg.SamplerConfig{
				Type:  jaeger.SamplerTypeConst,
				Param: 1, // 采样率，这里设置为1表示对每个追踪都进行采样
			},
			Reporter: &jaegercfg.ReporterConfig{
				LogSpans:           true, //启用LogSpan以记录每个跨度
				LocalAgentHostPort: viper.GetString("jarger.address"),
			},
			ServiceName: viper.GetString("jarger.name"),
		}

		tracer, closer, err := cfg.NewTracer(jaegercfg.Logger(jaeger.StdLogger))
		if err != nil {
			panic(err)
		}
		opentracing.SetGlobalTracer(tracer) //设置全局
		defer closer.Close()

		startSpan := opentracing.StartSpan(context.Request.URL.Path)
		defer startSpan.Finish()

		context.Set("tracer", tracer)
		context.Set("parentSpan", startSpan)
		context.Next()
	}
}
